const _model = {
  warrior: {
    id: "warrior_1",
    name: "凯萨",
    originalHealth: 100,
    health: 100,
    attack: 12,
    speed: 0.67,
    live: true
  },
  enemyArr: [{
    id: "enemy_1",
    name: "迦泰",
    originalHealth: 120,
    health: 120,
    attack: 15,
    speed: 0.4,
    live: true
  }, {
    id: "enemy_2",
    name: "欧罗",
    originalHealth: 80,
    health: 80,
    attack: 10,
    speed: 1.1,
    live: true
  }, {
    id: "enemy_3",
    name: "莉丝",
    originalHealth: 70,
    health: 70,
    attack: 8,
    speed: 2,
    live: true
  }],
  gameover: false,
  artUrl: "https://lf6-creative.dailygn.com/obj/tmg-gameres-static/build-template-assets/4a661d55935185b515f251e55765233c/action.png",
  art: {
    idle: "https://lf6-creative.dailygn.com/obj/tmg-gameres-static/build-template-assets/4a661d55935185b515f251e55765233c/action.png",
    play: "https://lf6-creative.dailygn.com/obj/tmg-gameres-static/build-template-assets/d58b07f4650e18939159658dd050e09d/action.gif"
  }
};
const _view = (_model) => {
  console.log("_model", _model);
  /**
   * 勇士数值
   */
  // 我方勇士
  const warrior = _model.warrior;
  if (warrior.health > 0) {
    setDiv(findDiv(warrior.id, "warrior"), `${warrior.name}，生命值：${warrior.health}，攻击力：${warrior.attack}，攻速：${warrior.speed}`);
  } else {
    if (warrior.live) {
      stopFun();
      alert(`很遗憾☹，我方勇士 ${warrior.name} 战斗失败，继续努力`);
      warrior.live = false;
      _model.gameover = true;
      delDiv(warrior.id);
    }
  }
  // 对手勇士
  const enemyArr = _model.enemyArr;
  enemyArr.forEach((v, k) => {
    if (v.health > 0) { setDiv(findDiv(v.id, "enemy"), `${v.name}，生命值：${v.health}，攻击力：${v.attack}，攻速：${v.speed}`); } else {
      if (v.live) {
        stopFun();
        const addHealth = Math.round(v.originalHealth / 3 * 2);
        const addAttack = v.attack > warrior.attack ? Math.round(v.attack / 3) : 0;
        const addSpeed = v.speed > warrior.speed ? Math.round(v.speed / 3) : 0;
        alert(`我方勇士 ${warrior.name} 战胜对手勇士 ${v.name} ，获得奖励，生命值：+${addHealth}${addAttack ? "，攻击力：+" + addAttack : ""}${addSpeed ? "，攻速：+" + addSpeed : ""}`);
        _model.warrior.health += addHealth;
        if (addAttack) _model.warrior.attack += addAttack;
        if (addSpeed) _model.warrior.speed += addSpeed;
        v.live = false;
        delDiv(v.id);
        delLabel(v);
      }
    }
  });
  // 战斗结束
  if (!enemyArr.map(v => v.live).includes(true) && !_model.gameover) {
    stopFun();
    alert(`恭喜☺，我方勇士 ${warrior.name} 在“勇士之战”中大获全胜`)
    _model.gameover = true;
  }
  /**
   * 勇士战场
   */
  // 勇士名称
  setDiv("self", warrior.name);
  // 选择列表
  selectList(_model.enemyArr);
  // 战斗场面
  actionArt(_model.artUrl);
};
const mv = (obj, callback, pointer) => {
  let single = true;
  callback.call(pointer, obj);
  const proxy = (_obj, callback, pointer) =>
    new Proxy(_obj, {
      set(target, property, value, receiver) {
        if (target[property] !== value) setTimeout(() => {
          if (!single) callback.call(pointer, obj);
        }, 0);
        Reflect.set(target, property, value, receiver);
        return true;
      },
    });
  const recursion = (_obj) => {
    for (const key in _obj) {
      ["[object Object]", "[object Array]"].includes(Object.prototype.toString.call(_obj[key])) &&
        (_obj[key] = proxy(_obj[key], callback, pointer)) && recursion(_obj[key]);
    }
  }
  recursion(obj)
  setTimeout(() => {
    single = false;
  }, 0);
  return proxy(obj, callback, pointer);
};
const findClass = (v) => document.getElementsByClassName(v)[0];
const findDiv = (name, parentName) => {
  let div = document.getElementById(name);
  if (!div) {
    div = document.createElement("div");
    div.id = name;
    findClass(parentName).appendChild(div);
  }
  return div;
}
const setDiv = (div, text) => {
  div = typeof div === "object" ? div : findClass(div);
  if (div.innerText != text) div.innerText = text;
}
const delDiv = (id) => {
  let div = document.getElementById(id);
  if (div) div.remove();
}
const actionArt = (url) => {
  let acitonImg = findClass("action");
  if (acitonImg.src !== url) acitonImg.src = url;
}
const findLabel = (v) => {
  let label = document.getElementById(`label_${v.id}`);
  let input = null;
  let div = null;
  if (!label) {
    label = document.createElement("label");
    input = document.createElement("input");
    div = document.createElement("div");
    label.appendChild(input);
    label.appendChild(div);
    findClass("select").appendChild(label);
    input.name = "selectOpponent";
    input.type = "radio";
  } else {
    input = label.getElementsByTagName("input")[0];
    div = label.getElementsByTagName("div")[0];
  }
  if (label.id != `label_${v.id}`) label.id = `label_${v.id}`;
  if (label.innerText != v.name) div.innerText = v.name;
  if (input.value != v.id) input.value = v.id;
}
const delLabel = (v) => {
  let label = document.getElementById(`label_${v.id}`);
  if (label) label.remove();
}
const selectList = (v) => {
  v.forEach(v => {
    if (v.live) findLabel(v);
  })
}
const actionPool = {};
const startFun = () => {
  let id = null;
  for (let v of document.getElementsByName("selectOpponent")) {
    if (v.checked) { id = v.value; break; }
  }
  if (!id) {
    alert("请选择对手勇士");
    return;
  }
  if (model.warrior.health <= 0 || !model.warrior.live) {
    alert("生命值不足，无法继续战斗");
    return;
  }
  console.log("=============== 开始战斗 ================");
  model.artUrl = model.art.play;
  const warrior = model.warrior;
  for (const key in model.enemyArr) {
    const enemy = model.enemyArr[key];
    if (enemy.id === id) {
      if (actionPool[warrior.id]) clearInterval(actionPool[warrior.id]);
      actionPool[warrior.id] = setInterval(() => {
        enemy.health -= warrior.attack;
      }, (1 / warrior.speed) * 1000);
      if (actionPool[enemy.id]) clearInterval(actionPool[enemy.id]);
      actionPool[enemy.id] = setInterval(() => {
        warrior.health -= enemy.attack;
      }, (1 / enemy.speed) * 1000);
      break;
    }
  }
}
const stopFun = () => {
  console.log("=============== 停止战斗 ================");
  model.artUrl = model.art.idle;
  for (const key in actionPool) {
    if (actionPool[key]) clearInterval(actionPool[key]);
  }
}
window.onload = () => {
  window.model = mv(_model, _view, this);
};
findClass("start").onclick = () => startFun();
findClass("stop").onclick = () => stopFun();
